<?php

namespace App\Libs\Company\SheetTemplateHandler\Aggregate;

use App\Libs\Company\SheetTemplateHandler\Aggregate\AbstractTemplate;
use App\Libs\Company\SheetTemplateHandler\Manager;
use App\Models\AggregateReport;
use App\Models\SheetTemplate;
use App\Models\Task;
use Illuminate\Support\Facades\Log;

class Template227 extends AbstractTemplate
{
    public $dataStartRow = 3;

    protected $lastMonthData;

    protected static $monthColumnMap = [
        '1' => 6,
        '2' => 9,
        '3' => 12,
        '4' => 15,
        '5' => 18,
        '6' => 21,
        '7' => 24,
        '8' => 27,
        '9' => 30,
        '10' => 33,
        '11' => 36,
        '12' => 39,
    ];

    public function generateAbstract()
    {
        $this->renderHeader();
        $this->output['sheets']['sheet-01']['cellData']['0']['0'] = $this->createTitleCell("{$this->task->year}年{$this->template->name}");

        $this->lastMonthData = $this->getLastMonthData();

        $reportTemplates = $this->template->reportTemplates()->wherePivot('frequency', $this->task->frequency)->get();
        foreach ($reportTemplates as $rt) {
            $task = Task::where([
                'sheet_template_id' => $rt->id,
                'frequency' => $this->task->frequency,
                'year' => $this->task->year,
                'key' => $this->task->key,
                'status' => Task::STATUS_COMPLETED,
            ])
                ->first();

            $currRow = $this->dataStartRow;
            $sn = 1;
            foreach ($task->subTasks as $subTask) {
                $handler = Manager::createReportHandler(SheetTemplate::find($task->sheet_template_id), $subTask);
                $data = $handler->getData();

                $count = 0;
                try {
                    foreach ($data as $row) {
                        if (empty($row[1]['v'])) {
                            continue;
                        }
                        $newRow = [
                            ['v' => $sn++, 's' => 'CENTER'],
                            ['v' => str_replace('旅游局', '', $subTask->district->name), 's' => 'CENTER'],
                            ['v' => $row[1]['v'], 't' => 1, 's' => 'CENTER'],
                            ['v' => $row[2]['v'], 't' => 1, 's' => 'CENTER'],
                            ['v' => $row[3]['v'], 't' => 2],
                            ['v' => $row[4]['v'], 't' => 2],
                        ];
                        foreach (self::$monthColumnMap as $month => $column) {
                            if ($month == $task->key) {
                                $newRow[$column] = ['v' => $row[5]['v'], 't' => 2];
                                $newRow[$column + 1] = ['v' => $row[6]['v'], 't' => 2];
                                $newRow[$column + 2] = ['v' => $row[7]['v'], 't' => 2];
                                $newRow[42] = ['v' => $row[8]['v'] ?? '', 't' => 1];
                                break;
                            }
                            if (isset($this->lastMonthData[$newRow[2]['v']])) {
                                $newRow[$column] = ['v' => $this->lastMonthData[$newRow[2]['v']][$column]['v'] ?? 0, 't' => 2];
                                $newRow[$column + 1] = ['v' => $this->lastMonthData[$newRow[2]['v']][$column + 1]['v'] ?? 0, 't' => 2];
                                $newRow[$column + 2] = ['v' => $this->lastMonthData[$newRow[2]['v']][$column + 2]['v'] ?? 0, 't' => 2];
                            }
                        }
                        $this->output['sheets']['sheet-01']['cellData'][] = $newRow;

                        $count++;
                    }
                } catch (\Throwable $th) {
                    Log::error('填报表异常 id:' . $subTask->id);
                    throw $th;
                }

                $this->dataEndRow = $currRow + $count - 1;
                $this->output['sheets']['sheet-01']['mergeData'][] = [
                    'startRow' => $currRow,
                    'endRow' => $this->dataEndRow,
                    'startColumn' => 1,
                    'endColumn' => 1,
                ];
                $currRow = $this->dataEndRow + 1;
            }
        }

        $this->renderFooter();
        return $this->output;
    }

    public function getLastMonthData()
    {
        if ($this->task->key == 1) {
            $year = $this->task->year - 1;
            $key = 12;
        } else {
            $year = $this->task->year;
            $key = (int) $this->task->key - 1;
        }

        $lastAggregateReport = AggregateReport::where([
            'sheet_template_id' => $this->template->id,
            'frequency' => $this->task->frequency,
            'year' => $year,
            'key' => $key,
        ])
            ->first();
        if (!$lastAggregateReport) {
            return [];
        }

        $data = [];
        $i = $this->dataStartRow;
        while (1) {
            $row = $lastAggregateReport->data['sheets']['sheet-01']['cellData'][$i++] ?? [];
            if (!isset($row[2]['v'])) {
                break;
            }
            $data[$row[2]['v']] = $row;
        }
        return $data;
    }
}
